#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 
###----------1、文件说明----------### 
''' 
* 说明：conan安装配置文件
* 时间：
* 文件：
* 作者：Smile
* 版本：0.1
* 库版本: 
 - conan: 2.14.0
* 备注： 
'''
import os,sys
from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout, CMakeDeps
from conan.tools.system import package_manager
from pprint import pprint
import platform
import importlib
from datetime import datetime
import time

def getClassValue(sclass):
    '''
    获取类的子属性
    版本: 0.1
    :param sclass:
    :return:
    '''
    from types import FunctionType, BuiltinFunctionType, MethodType

    print("Get Class ", type(sclass))
    for i in dir(sclass):
        tmp = getattr(sclass, i)
        if isinstance(tmp, FunctionType) or isinstance(tmp, BuiltinFunctionType):
            print(i, "\t", type(tmp), "Function")
        else:
            print(i, "\t", type(tmp), tmp)

manager_mapping = {"Apt": ["Linux", "ubuntu", "kylin", "debian", "raspbian", "linuxmint", 'astra', 'elbrus', 'altlinux', 'pop'],
                    "Apk": ["alpine"],
                    "Yum": ["pidora", "scientific", "xenserver", "amazon", "oracle", "amzn",
                            "almalinux", "rocky"],
                    "Dnf": ["fedora", "rhel", "centos", "mageia", "nobara"],
                    "Brew": ["Darwin"],
                    "PacMan": ["arch", "manjaro", "msys2", "endeavouros"],
                    "Chocolatey": ["Windows"],
                    "Zypper": ["opensuse", "sles"],
                    "Pkg": ["freebsd"],
                    "Pkgutil": ["Solaris"]}

class SoftConfigRecipe(ConanFile):
    name = "transmissioninstall"
    version = "0.1"
    package_type = "build-scripts"

    # 个人信息
    license = "MIT"
    author = "<OSmile> <whghcyx@outlook.com>"
    url = "https://whg555.github.io"
    description = "readme description"
    topics = ("<Put some tag here>", "<here>", "<and here>")

    # 二进制配置
    settings = "os", "compiler", "build_type", "arch"

    # 针对特定系统的安装包
    packages = {
        "ubuntu" :  {
            "default" : ["transmission-daemon"], # 当前系统通用的包
            "20" : ["transmission-daemon"], # 特定版本号的包
            "22" : ["transmission-daemon"], # 特定版本号的包
        },
        "kylin" : {
            "default" : ["transmission-daemon"], # 当前系统通用的包
            "v10" :  ["transmission-daemon"], # 当前系统通用的包
        },
        "default" : {
            "default" : ["transmission-daemon"]
        }
    }

    def config_options(self):
        '''
        针对系统，对配置命令做一些修改
        <1>conan install .
        <1>conan create .
        <test><1>conan create .
        '''
        self.starttime = datetime.now()
        print("\033[43;34mOSmile-->", "config_options", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        print(">OS System Info")
        pprint(self.settings.values_list)
        # pprint(self.serialize())
        print("self.conf", self.conf)

        # 获取系统版本信息
        os_name = platform.system()
        self.os_name = self.os_version = self.os_base =  ""
        self.os_base = os_name
        if os_name in ["Linux", "FreeBSD"]:
            import distro
            self.os_name = distro.id() or os_name
            self.os_version = distro.version(best=True).split(".")[0]
        elif os_name == "Windows" and self.settings.get_safe("os.subsystem") == "msys2":
            self.os_name = "msys2"
            self.os_version = ""
        print("System   -->", self.os_base)
        print("OSSystem -->", self.os_name)
        print("Version  -->", self.os_version)

    def configure(self):
        '''
        <2>conan install .
        <2>conan create .
        <test><2>conan create .
        '''
        print("\033[43;34mOSmile-->", "configure", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        if self.os_name == "kylin":
            self.conf.define("tools.system.package_manager:tool", "apt-get")
        self.conf.define("tools.system.package_manager:mode", "install")
        self.conf.define("tools.system.package_manager:sudo", True)

    def layout(self):
        '''
        <3>conan install .
        <3>conan create .
        <test><3>conan create .
        '''
        print("\033[43;34mOSmile-->", "layout", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")

    def system_requirements(self):
        '''
        安装需要的软件
        <4>conan install .
        <4>conan create .
        <test><4>conan create .
        '''
        print("\033[43;34mOSmile-->", "system_requirements", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        if platform.system() in ["Linux", "FreeBSD"]:
            # 获取编译工具
            for tool, distros in manager_mapping.items():
                if self.os_name in distros:
                    break
            # 查找需要安装的包
            os_name_key = self.os_name if (self.os_name in self.packages.keys()) else "default"
            os_version_key = self.os_version if (self.os_version in self.packages[os_name_key].keys()) else "default"
            softs = self.packages.get(os_name_key).get(os_version_key)
            print("安装软件包-->", softs)
            softtool = getattr(package_manager, tool)(self)
            softtool.install(softs, update=False, check=True)
        elif platform.system() == "Windows" and self.settings.get_safe("os.subsystem") == "msys2":
            os_name = "msys2"

    def generate(self):
        '''
        配置已经安装的软件
        <5>conan install .
        <5>conan create .
        '''
        print("\033[43;34mOSmile-->", "generate", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        self.run("sudo systemctl stop transmission-daemon")
        config = """{
    "alt-speed-down": 50,
    "alt-speed-enabled": false,
    "alt-speed-time-begin": 540,
    "alt-speed-time-day": 127,
    "alt-speed-time-enabled": false,
    "alt-speed-time-end": 1020,
    "alt-speed-up": 50,
    "bind-address-ipv4": "0.0.0.0",
    "bind-address-ipv6": "::",
    "blocklist-enabled": false,
    "blocklist-url": "http://www.example.com/blocklist",
    "cache-size-mb": 4,
    "dht-enabled": true,
    "download-dir": "/var/lib/transmission-daemon/downloads",
    "download-limit": 100,
    "download-limit-enabled": 0,
    "download-queue-enabled": true,
    "download-queue-size": 5,
    "encryption": 1,
    "idle-seeding-limit": 30,
    "idle-seeding-limit-enabled": false,
    "incomplete-dir": "/var/lib/transmission-daemon/Downloads",
    "incomplete-dir-enabled": false,
    "lpd-enabled": false,
    "max-peers-global": 200,
    "message-level": 1,
    "peer-congestion-algorithm": "",
    "peer-id-ttl-hours": 6,
    "peer-limit-global": 200,
    "peer-limit-per-torrent": 50,
    "peer-port": 51413,
    "peer-port-random-high": 65535,
    "peer-port-random-low": 49152,
    "peer-port-random-on-start": false,
    "peer-socket-tos": "default",
    "pex-enabled": true,
    "port-forwarding-enabled": false,
    "preallocation": 1,
    "prefetch-enabled": true,
    "queue-stalled-enabled": true,
    "queue-stalled-minutes": 30,
    "ratio-limit": 2,
    "ratio-limit-enabled": false,
    "rename-partial-files": true,
    "rpc-authentication-required": true,
    "rpc-bind-address": "0.0.0.0",
    "rpc-enabled": true,
    "rpc-host-whitelist": "",
    "rpc-host-whitelist-enabled": true,
    "rpc-password": "{0f9f7cf4c186473fb01389f7d8103250e3c6b3b6L/Vqd3tc",
    "rpc-port": 9091,
    "rpc-url": "/transmission/",
    "rpc-username": "osmile",
    "rpc-whitelist": "127.0.0.1",
    "rpc-whitelist-enabled": false,
    "scrape-paused-torrents-enabled": true,
    "script-torrent-done-enabled": false,
    "script-torrent-done-filename": "",
    "seed-queue-enabled": false,
    "seed-queue-size": 10,
    "speed-limit-down": 100,
    "speed-limit-down-enabled": false,
    "speed-limit-up": 100,
    "speed-limit-up-enabled": false,
    "start-added-torrents": true,
    "trash-original-torrent-files": false,
    "umask": 18,
    "upload-limit": 100,
    "upload-limit-enabled": 0,
    "upload-slots-per-torrent": 14,
    "utp-enabled": true
}"""
        with open("settings.json", "x", encoding="utf-8") as f:
            f.write(config)
        self.run("sudo mv settings.json /etc/transmission-daemon/settings.json", ignore_errors=True)
        self.run("wget https://github.com/jayzcoder/TrguiNG/releases/download/trguing-web-v1.3.0-zh-240607a/trguing-web-v1.3.0-zh-240607a.zip")
        self.run("sudo mv /usr/share/transmission/web /usr/share/transmission/web-bak")
        self.run("sudo unzip trguing-web-v1.3.0-zh-240607a.zip -d /usr/share/transmission/web")

        self.run("sudo systemctl daemon-reload")
        self.run("sudo systemctl enable transmission-daemon")
        self.run("sudo systemctl start transmission-daemon")
        self.run("sudo systemctl status transmission-daemon")

    def build(self):
        '''
        <6>conan create .
        '''
        print("\033[43;34mOSmile-->", "build", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")

    def package(self):
        '''
        <7>conan create .
        '''
        print("\033[43;34mOSmile-->", "package", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")

    def package_info(self):
        '''
        <8>conan create .
        <test><5>conan create .
        '''
        print("\033[43;34mOSmile-->", "package_info", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")


